package com.outsource.framework.util.unicom.news.sso;

import org.amplatform.controlpanel.properties.GlobalConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.outsource.framework.util.common.GodGenerator;
import com.outsource.framework.util.unicom.news.sso.httpclient.Broswer;
import com.outsource.framework.util.unicom.news.sso.httpclient.HttpResponseWrapper;
import com.outsource.framework.util.unicom.news.sso.httpclient.IBroswer;

public class SsoByHttp {
	private static final Log log = LogFactory.getLog(SsoByHttp.class);
	
	private static String ssoid_source=GlobalConfig.getProperty("app.sso.ssoid_source");
	private static String ssopw_source = GlobalConfig.getProperty("app.sso.ssopw_source");
	private static String ssogatewayurl = GlobalConfig.getProperty("app.sso.ssogatewayurl");
	private static String ssoreturnurl1 = GlobalConfig.getProperty("app.sso.ssoreturnurl1");
	private static String ssoreturnurl2 = GlobalConfig.getProperty("app.sso.ssoreturnurl2");
	private static String ssoreturnurl3 = GlobalConfig.getProperty("app.sso.ssoreturnurl3");
	
	public static String requestSso(String mobile,int type){
		log.info("request sso start::::");
		long timeStamp = System.currentTimeMillis();
		
		String woid = getRequestQueryString(mobile,timeStamp);
		String requesturl = getRequestUrl(woid,type);
		log.info("request url::::"+requesturl);
		IBroswer ib = new Broswer();
		ib.open();
			HttpResponseWrapper httpresponse = ib.get(requesturl);
			String body = httpresponse.getBody();
		ib.close();
		log.info("request sso end:::::");
		return body;
	}
	
	public static String requestUrl(String mobile,int type){
		long timeStamp = System.currentTimeMillis();
		
		String woid = getRequestQueryString(mobile,timeStamp);
		String requesturl = getRequestUrl(woid,type);
		log.info("request url:::::"+requesturl);
		return requesturl;
	}
	
	private static String getRequestQueryString(String mobile,long timeStamp){
		StringBuffer sb = new StringBuffer();
		sb = sb.append(ssoid_source).append(",").append(timeStamp).append(",").append(mobile).append(",").append(getMD5String(mobile,timeStamp));
		return sb.toString();
	}
	
	private static String getMD5String(String mobile,long timeStamp){
		StringBuffer tomd5 = new StringBuffer();
		tomd5 = tomd5.append(ssoid_source).append(",").append(timeStamp).append(",").append(ssopw_source).append(",").append(mobile);
		return GodGenerator.getMD5Digest(tomd5.toString());
	}
	
	public static String getRequestUrl(String woid,int type){
		String requesturl = "";
		switch (type) {
		case 0:
			requesturl = ssogatewayurl+"?woid="+woid+"&returnurl="+ssoreturnurl1;
			break;
		case 1:
			requesturl = ssogatewayurl+"?woid="+woid+"&returnurl="+ssoreturnurl2;
			break;
		case 2:
			requesturl = ssogatewayurl+"?woid="+woid+"&returnurl="+ssoreturnurl3;
			break;
		default:
			break;
		}
		return requesturl;
	}
}
